<template>
  <div>
    <el-upload list-type="picture-card" name="file" :class="{'my_upload-view': disable}" :disabled="disable" :file-list="imageListView" :accept="acceptTypes" :limit="limit" :before-upload="handleBeforeUpload" :on-error="handleError" :on-exceed="handleExceed" :http-request="handleRequest">
      <i class="el-icon-plus"></i>
      <div slot="file" slot-scope="{file}" class="my_upload-list">
        <img class="my_upload-image" :src="file.url" alt />
        <span v-if="!disable" :class="file.status==='success' ? 'is-ok' : 'is-begin'" class="my_upload-load"></span>

        <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
            <i class="el-icon-zoom-in"></i>
          </span>
          <span v-if="!disable && file.status === 'success'" class="el-upload-list__item-delete" @click="beforeDelete(file)">
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
      <div v-if="!disable" slot="tip" class="picture-text">{{acceptTips}}</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>
  </div>
</template>
<script>
import { UploadImage } from "@/api/config";
import { syncFileToBlog } from "@/util/util";

const IMAGE_TYPE_MAP = {
  jpg: "image/jpeg",
  png: "image/png",
  gif: "image/gif"
};

export default {
  name: "upload",
  props: {
    image: {},
    imageKey: {},
    disable: {
      type: Boolean,
      default: false
    },
    repeat: {
      type: Boolean,
      default: false
    },
    accept: {
      type: Array,
      default: () => ["jpg", "png"]
    },
    type: {
      type: Number,
      default: 1
    },
    putting: {
      type: String
    }
  },
  data() {
    return {
      limit: this.repeat ? 6 : 1,
      dialogImageUrl: "",
      imageListView: [],
      dialogVisible: false
    };
  },
  created() {
    if (!this.repeat) {
      this.imageListView = this.image
        ? [{ key: this.currentImageKeys, url: this.image }]
        : [];
    } else {
      this.imageListView = this.image
        ? this.image.map((url, indx) => ({
            key: this.currentImageKeys[indx],
            url
          }))
        : [];
    }
    console.log(this.imageListView);
  },
  computed: {
    acceptTypes() {
      return this.accept.map(type => IMAGE_TYPE_MAP[type] || type).join(",");
    },
    acceptTips() {
      return `只支持${this.accept.join("/")}格式`;
    },
    currentImageKeys() {
      return this.imageKey.split(",");
    }
  },
  methods: {
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    beforeDelete(file) {
      if (file.status !== "success") {
        return false;
      }
      this.imageListView.pop();
      this.updateValue();
      return false;
    },
    handleExceed() {
      this.$message({
        type: "warning",
        message: `最多只能上传${this.limit}张图片，如需更改请删除旧的图片`
      });
    },
    async handleRequest(file) {
      this.$emit("update:putting", "图片上传中，请稍后");
      // file to blob
      const { blob, blobError } = await syncFileToBlog(file.file);
      if (blobError) {
        this.thorwError(blobError);
        return;
      }

      const { data, error } = await UploadImage(blob, file.file.type);
      if (error) {
        this.thorwError(error);
        return;
      }
      let imageFile = {};
      imageFile.name = file.name;
      imageFile.url = data.bussData.downloadUrl || file.url;
      imageFile.key = data.bussData.fileKey || file.uid;
      imageFile.uid = file.uid;
      imageFile.status = "success";

      this.$nextTick(() => {
        this.imageListView[this.imageListView.length] = imageFile;
        this.updateValue();
      });
    },
    thorwError(error) {
      this.$message({
        type: "error",
        message: String(error)
      });
      this.imageListView.pop();
      this.$emit("update:putting", "");
    },
    handleBeforeUpload(file) {
      if (this.accept.length && !this.acceptTypes.includes(file.type)) {
        this.$message({
          type: "error",
          message: this.acceptTips
        });
        return false;
      }
      return true;
    },
    updateValue() {
      let imageUrls = [];
      let imageKeys = [];
      this.imageListView.forEach(file => {
        imageUrls.push(file.url);
        imageKeys.push(file.key);
      });
      if (!this.repeat) {
        imageUrls = imageUrls[0] || "";
        imageKeys = imageKeys[0] || "";
      } else {
        imageKeys = imageKeys.join(",");
      }
      this.$emit("update:image", imageUrls);
      this.$emit("update:imageKey", imageKeys);
      this.$emit("update:putting", "");
    }
  }
};
</script>
<style lang="scss">
.my_upload {
  &-view > .el-upload {
    display: none;
  }
  &-image {
    position: absolute;
    top: 50%;
    left: 50%;
    display: block;
    max-height: 100%;
    transform: translate(-50%, -50%);
  }
  &-load {
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    height: 2px;
    background-color: #08d208;
    transition: all 0.4s ease-out;
    &.is-begin {
      width: 15%;
    }
    &.is-ok {
      width: 100%;
    }
  }
}
</style>

